package com.caiyi.financial.nirvana.sms.task;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.HttpClientUtil;
import com.caiyi.financial.nirvana.sms.util.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Mario on 2017/12/21 0021.
 * 推送Msg任务
 */
public class PushReportTask implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(PushReportTask.class);

    private SendQueueEntity entity;

    private final static String SUCCESS = "SUCCESS";

    /**
     * 构造函数
     *
     * @param entity
     */
    public PushReportTask(SendQueueEntity entity) {
        this.entity = entity;
    }

    @Override
    public void run() {
        try {
            Map<String, String> pushMap = new HashMap<>();
            pushMap.put("account", entity.getAccount());
            pushMap.put("batchId", entity.getBatchId());
            pushMap.put("phone", entity.getPhone());
            pushMap.put("status", entity.getStatus().toString());
            pushMap.put("result", entity.getResult());
            pushMap.put("uid", entity.getUid());
            pushMap.put("receiveTime", CommUtil.YYYY_MM_DD_HH_MM_SS.get().format(entity.getReceiveTime()));
            String key = String.format(JedisKey.SMS_USER, entity.getAccount());
            SmsUser user = JSON.parseObject(JedisService.get(key), SmsUser.class);
            String sign = SignUtil.createSign(pushMap, user.getPassword());
            pushMap.put("sign", sign);
            String pushJson = JSON.toJSONString(pushMap);
            String result = HttpClientUtil.doPost(entity.getNotifyUrl(), pushJson);
            if (!SUCCESS.equalsIgnoreCase(result)) {
                result = HttpClientUtil.doPost(entity.getNotifyUrl(), pushJson);
            }
            logger.info("push notifyUrl : {}, pushJson : {}, result : {}, password : {}", entity.getNotifyUrl(), pushJson, result, user.getPassword());
        } catch (Exception e) {
            logger.error("PushReportTask error !!! ", e);
        }
    }
}
